﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.UI.WebControls;

namespace IntroduceCompany.Util
{
    public class ThumbnailClass
    {

        /// <summary>
        /// Replace all special character and space to hyphen character
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string standardImageName(string name)
        {
            return (name.Replace(' ', '-').Replace('.', '-').Replace('/', '-').Replace('+', '-').Replace('*', '-').Replace('?', '-').Replace('!', '-').Replace('@', '-').Replace('~', '-').Replace('#', '-').Replace('$', '-').Replace('%', '-').Replace('^', '-').Replace('(', '-').Replace(')', '-').Replace('=', '-').Replace('|', '-').Replace('{', '-').Replace('}', '-').Replace(':', '-').Replace('"', '-').Replace(';', '-').Replace('<', '-').Replace('>', '-').Replace("'", "-").Replace("]", "-").Replace("[", "-").Replace("\\", "-").Replace(",", "-").Replace("“", "").Replace("”", "").Replace("_", "-")).ToLower();
        }

        private static readonly string[] VietNamChar = new string[] 
    { 
        "aAeEoOuUiIdDyY", 
        "áàạảãâấầậẩẫăắằặẳẵ", 
        "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ", 
        "éèẹẻẽêếềệểễ", 
        "ÉÈẸẺẼÊẾỀỆỂỄ", 
        "óòọỏõôốồộổỗơớờợởỡ", 
        "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ", 
        "úùụủũưứừựửữ", 
        "ÚÙỤỦŨƯỨỪỰỬỮ", 
        "íìịỉĩ", 
        "ÍÌỊỈĨ", 
        "đ", 
        "Đ", 
        "ýỳỵỷỹ", 
        "ÝỲỴỶỸ"
    };

        /// <summary>
        /// Replace Vietnamese character to English character
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string filter(string str)
        {
            //Thay thế và lọc dấu từng char      
            for (int i = 1; i < VietNamChar.Length; i++)
            {
                for (int j = 0; j < VietNamChar[i].Length; j++)
                    str = str.Replace(VietNamChar[i][j], VietNamChar[0][i - 1]);
            }
            return str;
        }




        /// <summary>
        /// Manual resize and upload image to server
        /// </summary>
        /// <param name="fileUp"></param>
        /// <param name="fullImagePath">path to save </param>
        /// <param name="imageName">Filename with extension</param>
        /// <param name="imageHeight"></param>
        /// <param name="imageWidth"></param>
        /// <returns>Ex:Nguyen-Thi-2.jpg</returns>
        public String UploadImage(HttpPostedFileBase fileUp, String fullImagePath, String imageName, int imageHeight, int imageWidth, String oldImage)
        {
            string fileExtension = "";
            string newImage = "";
            try
            {

                imageName = ThumbnailClass.filter(Path.GetFileNameWithoutExtension(imageName).ToLower().Trim());
                imageName = ThumbnailClass.standardImageName(imageName);

                fileExtension = Path.GetExtension(fileUp.FileName).ToLower().Trim();
                //newImage = imageName + "-" + DateTime.Now.Ticks + fileExtension;
                newImage = imageName +  fileExtension;


                if (fileExtension == ".jpg" || fileExtension == ".gif" || fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".bmp" || fileExtension == ".tiff")
                {
                    byte[] orginaryData = new byte[fileUp.ContentLength];
                    fileUp.InputStream.Position = 0;
                    fileUp.InputStream.Read(orginaryData, 0, fileUp.ContentLength);

                    byte[] data = ImageMedia.Create(orginaryData).Resize(imageWidth, imageHeight).ToByteArray();
                    FileStream file = File.Create(fullImagePath + newImage);
                    file.Write(data, 0, data.Length);
                    file.Close();

                    //Delete old image
                    if (oldImage != newImage && oldImage != "")
                    {
                        string LocalFile = fullImagePath + oldImage;
                        if (File.Exists(LocalFile))
                            File.Delete(LocalFile);
                    }

                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
                return "";
            }
            return newImage;
        }



        public static String ImageNameStandardization(String imageName)
        {
            imageName = ThumbnailClass.filter(imageName.ToLower().Trim());
            imageName = ThumbnailClass.standardImageName(imageName);
            return imageName;
        }


        /// <summary>
        /// Auto resize horizontal image and upload to server
        /// </summary>
        /// <param name="fileUp"></param>
        /// <param name="fullImagePath"></param>
        /// <param name="newHeight"></param>
        /// <param name="oldImageName"></param>
        /// <param name="newImageName">Image</param>
        /// <returns></returns>
        public String UploadImage1(HttpPostedFileBase fileUp, String fullImagePath, int newHeight, String oldImageName, String newImageName)
        {
            string fileExtension = "";
            try
            {
               // newImageName = ThumbnailClass.filter(newImageName.ToLower().Trim());
               // newImageName = ThumbnailClass.standardImageName(newImageName);

                fileExtension = Path.GetExtension(fileUp.FileName).ToLower().Trim();
            //    newImageName = newImageName + "-" + DateTime.Now.Ticks + fileExtension;
                newImageName = newImageName + fileExtension;
               

                if (fileExtension == ".jpg" || fileExtension == ".gif" || fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".bmp" || fileExtension == ".tiff")
                {
                    byte[] orginaryData = new byte[fileUp.ContentLength];
                    fileUp.InputStream.Position = 0;
                    fileUp.InputStream.Read(orginaryData, 0, fileUp.ContentLength);

                    ImageMedia img = ImageMedia.Create(orginaryData);

                    float imgWidth = img.Width;
                    float imgHeight = img.Height;
                    if (imgHeight > newHeight)
                    {
                    float imgRatio = newHeight / imgHeight;
                    
                    imgWidth = imgWidth * imgRatio;
                    imgHeight = newHeight;
                    img.Resize((int)imgWidth, (int)imgHeight);
                    }


                    //byte[] data = img.ToByteArray();
                    //FileStream file = File.Create(fullImagePath + newImageName);
                    //file.Write(data, 0, data.Length);
                    //file.Close();

                    File.WriteAllBytes(fullImagePath + newImageName, img.ToByteArray());

                    //Delete old image
                    if (oldImageName != "")
                    {
                        string LocalFile = fullImagePath + oldImageName;
                        if (File.Exists(LocalFile))
                            File.Delete(LocalFile);
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
                return "";
            }
            return newImageName;
        }


        /// <summary>
        /// Auto resize horizontal image and upload to server (Auto cut filename if length > 190)
        /// </summary>
        /// <param name="fileUp"></param>
        /// <param name="fullImagePath"></param>
        /// <param name="newHeight"></param>
        /// <param name="oldImageName"></param>
        /// <param name="newImageName">Image+DateTime.Now.Ticks</param>
        /// <returns>filename</returns>
        public String UploadImage2(HttpPostedFileBase fileUp, String fullImagePath, int newHeight, String oldImageName, String newImageName)
        {
            string fileExtension = "";
            try
            {
                newImageName = ThumbnailClass.filter(newImageName.ToLower().Trim());
                newImageName = ThumbnailClass.standardImageName(newImageName);

                fileExtension = Path.GetExtension(fileUp.FileName).ToLower().Trim();
                //Cut filename if length > 190
                newImageName = newImageName.Length > 190 ? newImageName.Substring(0, 190) : newImageName;
                newImageName = newImageName + fileExtension;


                if (fileExtension == ".jpg" || fileExtension == ".gif" || fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".bmp" || fileExtension == ".tiff")
                {
                    byte[] orginaryData = new byte[fileUp.ContentLength];
                    fileUp.InputStream.Position = 0;
                    fileUp.InputStream.Read(orginaryData, 0, fileUp.ContentLength);

                    ImageMedia img = ImageMedia.Create(orginaryData);

                    float imgWidth = img.Width;
                    float imgHeight = img.Height;
                    if (imgHeight > newHeight)
                    {
                        float imgRatio = newHeight / imgHeight;

                        imgWidth = imgWidth * imgRatio;
                        imgHeight = newHeight;
                        img.Resize((int)imgWidth, (int)imgHeight);
                    }
                    //byte[] data = img.ToByteArray();
                    //FileStream file = File.Create(fullImagePath + newImageName);
                    //file.Write(data, 0, data.Length);
                    //file.Close();

                    File.WriteAllBytes(fullImagePath + newImageName, img.ToByteArray());

                    //Delete old image
                    if (oldImageName != "")
                    {
                        string LocalFile = fullImagePath + oldImageName;
                        if (File.Exists(LocalFile))
                            File.Delete(LocalFile);
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
                return "";
            }
            return newImageName;
        }


    }
}